import { defineStore } from 'pinia'

export const useOrderStore = defineStore('orderStore', () => {
  const { requestGetNew, requestPostNew } = useRequest()
  const { $mt } = useCommonPlugin()
  const state = reactive({
    orderAllList: [],
    orderNum: [],
    orderTitleList: [
      {
        title: $mt('All'),
        orderStatus: '',
      },
      {
        title: $mt('Pending'),
        orderStatus: 'PENDING',
      },
      {
        title: $mt('Success'),
        orderStatus: 'SUCCESS',
      },
      {
        title: $mt('Delivery Failed'),
        orderStatus: 'SHIPPING_FAIL',
      },
    ] as any[],
  })
  return {
    ...toRefs(state),
    async fetchOrderNum() {
      state.orderNum = await requestGetNew(`/app/order/analysis`, {}, { withAuth: true })
      state.orderTitleList = state.orderTitleList.map((item) => {
        const res = state.orderNum.find(({ orderStatus, count }) => orderStatus === item.orderStatus)
        const total = state.orderNum.reduce((total, { count }) => total + parseInt(count), 0)
        if (item.orderStatus === '') return { ...item, count: total }
        if (res) return { ...item, count: res.count }
        return { ...item, count: 0 }
      })
    },
    async getOrderList(num, size, status: string) {
      state.orderAllList = await requestGetNew(
        `/app/user/orders/${num}/${size}?orderStatus=${status}`,
        {},
        { withAuth: true },
      )
    },
  }
})
